#!/usr/bin/env python
# -*- coding: utf-8 -*
'''
PySoQt app
Created on 2010-06-15

@author: apito
'''

import os
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from Socjum import Socjum
import time
import hashlib
import urllib
import tempfile
#import sip #for Windows py2exe only for now
__version__='0.2.1'
reload(sys)
sys.setdefaultencoding('utf-8')
			
class Win(QtGui.QWidget):
	'''Create window for app and manage them
	'''
	#Get data for login
	def _message(self, text):
		data = ' %s - '% (time.strftime("%H:%M:%S",time.localtime()))
		
		message= data +text 
		self.statusBar.showMessage(message)
	def login(self):
		user = str(self.loginLineEdit.text())#Pobranie loginu z pola
		if len(user) < 1:
			self._message(u"Nie podano loginu.")
			return	
		else:
			password = str(self.passwordLineEdit.text())#Pobrabue hasła z pola 
			if len(password)<1:
				self._message(u"Nie podano hasła")
				return
			else:
				self._message(u'Logowanie..')
				log = socjum.login(user,password)
				print log
				if log is not None:
					self._message(log)
				else:
					self._ONLINE = True
					self.albumSelectHosts.clear()
					self.albumSelectHosts.addItems(socjum.Hosts) ##dodanie listy hostów społeczności użytkownika
					self.albumBox.show()
					self.resize(self.sizeHint())
					self._message(u"zalogowano użytkownika "+user)
					self.Albums=socjum.Galeria(socjum.Hosts)#utworzenie obiektu galerii i pobieranie informacji
					
					self.progressBarTimer = QtCore.QTimer()
					self.progressBarTimer.connect(self.progressBarTimer, QtCore.SIGNAL('timeout()'), self.progressBox.check)
					self.progressBarTimer.start(50)
					self.setMinimumSize(800, 500)
					self.albumBox.show()
					self.loginBox.hide()
					self.logoutButton.show()
					self.albumSelectHosts.connect(self.albumSelectHosts, QtCore.SIGNAL('activated(int)'), self.showAlbums)
					self.albumSelectAlbum.connect(self.albumSelectAlbum, QtCore.SIGNAL('currentIndexChanged(int)'),self.showAlbumInfo)
					showAlbumsTimer = QtCore.QTimer()		
					showAlbumsTimer.singleShot(3500, self.showAlbums)
					
	def logout(self):
		if self._ONLINE:
			self.Albums.stop()
			log =socjum.logout()
			if log == 1:
				self._message(u"Wylogowano")
				self.logoutButton.hide()
				self.albumBox.hide()
				self.loginBox.show()
				self._ONLINE = False
				self.albumSelectHosts.clear()
				self.albumSelectAlbum.clear()
				self.setMinimumSize(400, 100)
				self.resize(self.sizeHint())
				return True
			else:
				self._message(u'Błąd wylogowania')
				return False
		else:
			return True
	def zamknij(self):
		return self.logout()
	
	def showAlbums(self, force=''):
		if self.albumSelectHosts.count()==0:
			return
		host=self.albumSelectHosts.currentText()
		host=str(host)
		self.albumSelectAlbum.clear()
		try:
			print "Sprawdzanie czy istnieją albmumy dla ", host
			albums = self.Albums.Albums[host]
			if force=='force':
				raise KeyError #przeładowanie informacji o albumie
		except KeyError:
			if host != '':
				self.Albums.Albums[host]= {} #czyszczenie informacji dla danego hosta
				self.Albums.getAlbums(host)
				albums = self.Albums.Albums[host]
		for album in albums:
			self.albumSelectAlbum.addItem(albums[album]['title'], album)
	def reloadAlbums(self):
		self.showAlbums(force='force')
		
	def showAlbumInfo(self):
		album = self.albumSelectAlbum.itemData(self.albumSelectAlbum.currentIndex()).toString()
		album=str(album)
		host=self.albumSelectHosts.currentText()
		host=str(host)
		if self.albumSelectAlbum.count() == 0:
			return
		self.albumInfoTitle.setText(self.Albums.Albums[host][album]['title'])
		self.albumInfoAuthor.setText(u"Dodał: "+self.Albums.Albums[host][album]['author'])
		self.albumInfoPhotos.setText(u"Zdjęć: "+self.Albums.Albums[host][album]['photos'])
		pixmap =self.thumbPixmap(self.Albums.Albums[host][album]['thumbnail'])
	
		self.albumInfoThumbnail.setPixmap(pixmap)
		self.albumInfoThumbnail.repaint()
		if self.Albums.Albums[host][album]['add'] ==1:
			self.albumInfoButton.setDisabled(False)
			self.albumInfoButton.setToolTip(u'Wybierz zdjęcia, które chcesz dodać do albumu')
		else:
			self.albumInfoButton.setDisabled(True)
			self.albumInfoButton.setToolTip(u'Nie możesz dodawać zdjęć do tego albumu.')



	def getFiles(self):
		files = QtGui.QFileDialog.getOpenFileNames(self,
			u"Wybierz zdjęcia", '/home',
			u"Pliki obrazów ( *.jpg *.jpeg *.JPG *.JPEG  *.png *.PNG *.GIF *.gif *.tiff *.TIFF) ;; Wszystkie pliki (*.*)")
		if files:	
			self.filesListBox.addItems(files) #add fotos to list
			self.albumFilesAlbum.setText(str(self.albumSelectAlbum.itemData(self.albumSelectAlbum.currentIndex()).toString()))
			self.albumFilesAlbumName.setText(self.albumInfoTitle.text())
			self.albumFilesHost.setText(self.albumSelectHosts.currentText())
				
	
	
	def uploadFiles(self):
		#Uwaga zmienić na ==
		if  self._ONLINE == False:#zmiana
			self._message(u"Nie jesteś zalogowany")
			return

		count = self.filesListBox.count()
		if count > 0:#Na liście są pliki
			host= str(self.albumFilesHost.text())
			albumID =str(self.albumFilesAlbum.text())
			albumName=str(self.albumFilesAlbumName.text())
			print host, albumID, albumName
			if host is not None:
				photos=[]
				pack = self.packSize.currentText()
				packSize = pack.toInt()
				print packSize
				self.uploadButton.setDisabled(True)
				for i in range(0, count):
					file = self.filesListBox.item(i).text()
					file = file.toLocal8Bit()
					file=str(file)
					photos.append(file)			
				send, message = socjum.upload(host,albumID,photos, limit=packSize[0])
				if send is None:
					self._message(message)
					return
			
				send.start()##rozpoczęcie działania wątku
	
				self.progressBox.add(send, host, albumName, len(photos))##add thread object to object for display progressbar
#########dodanie uploadu
				self.filesListBox.clear()
				self.uploadButton.setEnabled(True)

	
	def closeEvent(self, event):
		if self.zamknij() and self.progressBox.abort():
			event.accept()
		else:
			self._message(u"Kończenie wątków zakończone niepowodzenim, spróbuj ponownie")
			event.ignore()
	
	class myPB(QtGui.QGroupBox):#
		def __init__(self):
			QtGui.QGroupBox.__init__(self, u"Status wysyłania")
			self.pbs=[]#lista pasków postępu
			self.lay = QtGui.QVBoxLayout() #układ pionowy
			self.setLayout(self.lay) #dodanie układu
		#thread - wątek wysyłający (size, sent, status, infor, running(), stop()
		#albumName - nazwa albumu, o ile podana
		#photos - liczba wysyłanych zdjęć
		def add(self,thread, host, albumName, photos):
			vLay = QtGui.QVBoxLayout()#layout na etykietę oraz layout paska postępu i przycisków
			hLay = QtGui.QHBoxLayout()#layout na pasek i przycisk kasowania	
			box = QtGui.QGroupBox()
			box.setLayout(vLay)
		
			title = u"Wysyłanie %s zdjęć do albumu %s na %s (Części: %s)" % (photos,albumName, host, thread.packs)
			infoLabel = QtGui.QLabel()
			bar = QtGui.QProgressBar()
			
			cButton = QtGui.QPushButton(QtGui.QIcon('icons/error.png'), '')
			cButton.setToolTip(u"Anuluj/Usuń zadanie")
			cButton.connect(cButton, QtCore.SIGNAL('clicked()'), thread.stop)
			cButton.connect(cButton, QtCore.SIGNAL('clicked()'), box, QtCore.SLOT('close()'))
			
			bar.setToolTip(title)
			vLay.addLayout(hLay)
			self.lay.addWidget(box)
			hLay.addWidget(bar)
			hLay.addWidget(infoLabel)
			hLay.addWidget(cButton)
			#dodanie wątku, paska i statusu do listy
			self.pbs.append([thread, bar, infoLabel]) 	
			
		def check(self):
			for thread, bar, info in self.pbs:
				if thread.status == 1:
					info.setText(u"Wysłano część %s z %s." % (thread.part, thread.packs) )
				if thread.status ==3: #Miniatury
					info.setText(u"Tworzenie miniatur część %s z %s." % (thread.part, thread.packs) )
					bar.setRange(0,0)
					bar.setValue(1)
				if thread.status == 4:
					info.setText(u"Wysyłanie %s z %s." % (thread.part, thread.packs) )
					bar.setRange(0,thread.size)
					bar.setValue(thread.sent)
				if thread.status ==2:
					self._message(thread.info)
					info.setText(thread.info)
				
		def abort(self):
			for thread, bar, info in self.pbs:
				thread.stop()
			return True
		
	def thumbPixmap(self,url):
		if url.startswith('http://'):
			m=hashlib.md5()
			m.update(url)
			key=m.hexdigest()
			pix = QtGui.QPixmap()
			if not self.thumbnailCache.find(key, pix):
				img = urllib.urlopen(url)
				pix.loadFromData(img.read())
				self.thumbnailCache.insert(key, pix)
			return pix	

		else:
			return QtGui.QPixmap(url)

	
	def __init__(self, parent=None ):  

			super(Win, self).__init__(parent)
			self._ONLINE = False
			self.statusBar = QtGui.QStatusBar()
			self.statusBar.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
			self._message(u'Zaloguj się do socjum.pl używając Swojego loginu i hasła.')
			'''
			Logowanie
			'''		
			self.loginBox = QtGui.QGroupBox(u"Logowanie do socjum.pl")
			loginBoxLayout=QtGui.QHBoxLayout()
			self.loginBox.setLayout(loginBoxLayout)
			self.loginBox.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
			loginBoxLayout.setAlignment(QtCore.Qt.AlignRight)
			#miejsce na logowanie do ukrycia
			self.loginBoxInputLayout = QtGui.QHBoxLayout()
			self.loginBoxInputLayout.setAlignment(QtCore.Qt.AlignLeft)
			loginBoxLayout.addLayout(self.loginBoxInputLayout)
			'''
			kontrolki logowania
			'''
			loginLabel = QtGui.QLabel(u"Login: ")#etykieta  logowania
			self.loginBoxInputLayout.addWidget(loginLabel)
			
			self.loginLineEdit = QtGui.QLineEdit()# input login
			self.loginLineEdit.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
			self.loginLineEdit.setMaximumWidth(160)
			self.loginBoxInputLayout.addWidget(self.loginLineEdit)
			
			passwordLabel = QtGui.QLabel(u"Hasło: ")#etykieta hasła
			self.loginBoxInputLayout.addWidget(passwordLabel)
			
			self.passwordLineEdit = QtGui.QLineEdit()#input password
			self.passwordLineEdit.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
			self.passwordLineEdit.setMaximumWidth(160)
			self.passwordLineEdit.setEchoMode(QtGui.QLineEdit.Password)#Hide password characters
			self.passwordLineEdit.connect(self.passwordLineEdit,QtCore.SIGNAL("returnPressed()"), self.login)
			self.loginBoxInputLayout.addWidget(self.passwordLineEdit)
			#
			#logowanie
			#
			loginButton = QtGui.QPushButton(QtGui.QIcon("icons/ok.png"),u"Zaloguj")
			loginButton.connect(loginButton, QtCore.SIGNAL("clicked()"), self.login)
			self.loginBoxInputLayout.addWidget(loginButton)
			#
			#wylogowanie
			#
			self.logoutButton= QtGui.QPushButton(QtGui.QIcon("icons/logout.png"), u'Wyl&oguj')
			self.logoutButton.connect(self.logoutButton, QtCore.SIGNAL("clicked()"), self.logout)
			self.logoutButton.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)	
			loginBoxLayout.addWidget(self.logoutButton)
			
			'''
			Przeglądarka albumów
			'''		
			#Box główny na albmumy
			self.albumBox = QtGui.QGroupBox(u'Albumy')
			albumBoxLayout = QtGui.QVBoxLayout()
			self.albumBox.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
			self.albumBox.setLayout(albumBoxLayout)
			#
			#wybór społeczności i galerii
			#
			albumSelectLayout = QtGui.QHBoxLayout()
			albumSelectLayout.setAlignment(QtCore.Qt.AlignLeft)
			albumBoxLayout.addLayout(albumSelectLayout)
			albumSelectLayout2 = QtGui.QHBoxLayout()
			albumSelectLayout2.setAlignment(QtCore.Qt.AlignLeft)
			albumBoxLayout.addLayout(albumSelectLayout2)
			
			albumSelectHostsLabel=QtGui.QLabel(u'Społeczność:')
			self.albumSelectHosts = QtGui.QComboBox()
			self.albumSelectHosts.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
			
			albumSelectAlbumLabel=QtGui.QLabel(u'Album:')
			self.albumSelectAlbum = QtGui.QComboBox()
			self.albumSelectAlbum.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
			
			self.albumReloadButton = QtGui.QPushButton(QtGui.QIcon("icons/reload-image.png"), u'&Odświ&eż')
			self.albumReloadButton.setToolTip(u'Pobiera ponownie listę albumów. Albumy są pobierane na starcie. Spróbuj wybrać społeczność jeszcze raz aby zobaczyć listę.')
			self.albumReloadButton.connect(self.albumReloadButton, QtCore.SIGNAL("clicked()"), self.reloadAlbums)
			
			#
			#dodanie widżetów do wyboru społecznośći
			#
			albumSelectLayout.addWidget(albumSelectHostsLabel)
			albumSelectLayout.addWidget(self.albumSelectHosts)
			albumSelectLayout2.addWidget(albumSelectAlbumLabel)
			albumSelectLayout2.addWidget(self.albumSelectAlbum)
			albumSelectLayout.addWidget(self.albumReloadButton)
			
			'''
			Przeglądarka Albumów: linia na przeglądarkę działań
			
			'''
			
			albumActionLayout = QtGui.QHBoxLayout()
			albumActionLayout.setAlignment(QtCore.Qt.AlignTop)
			albumBoxLayout.addLayout(albumActionLayout)
			#
			#box na informacje o albumie
			#
			albumInfoBox=QtGui.QGroupBox(u"Informacje")
			albumInfoBoxLayout = QtGui.QVBoxLayout()
			albumInfoBox.setLayout(albumInfoBoxLayout)
			albumInfoBox.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
			albumActionLayout.addWidget(albumInfoBox)
			#tytuł albumu
			self.albumInfoTitle = QtGui.QLabel(u'Nazwa albumu')
			self.albumInfoTitle.setWordWrap(True)
			albumInfoBoxLayout.addWidget(self.albumInfoTitle)
			albumInfoPhotoLayout = QtGui.QHBoxLayout()
			#
			#Thumbnail
			#
			#img = self.thumbPixmap()
			self.albumInfoThumbnail = QtGui.QLabel()
			#self.albumInfoThumbnail.setPixmap(img)
			self.thumbnailCache=QtGui.QPixmapCache()
			albumInfoPhotoLayout.addWidget(self.albumInfoThumbnail)
			albumInfoBoxLayout.addLayout(albumInfoPhotoLayout)
			albumInfoTextLayout=QtGui.QVBoxLayout()
			albumInfoPhotoLayout.addLayout(albumInfoTextLayout)
			
			self.albumInfoAuthor = QtGui.QLabel(u'Autor')
			albumInfoTextLayout.addWidget(self.albumInfoAuthor)
			self.albumInfoPhotos = QtGui.QLabel(u'Zdjęć')
			albumInfoTextLayout.addWidget(self.albumInfoPhotos)
			
			self.albumInfoButton = QtGui.QPushButton(QtGui.QIcon("icons/open-image.png"), u'&Dodaj zdjęcia')
			self.albumInfoButton.setToolTip(u'Nie możesz dodać zdjęć do tego albumu.')
			self.albumInfoButton.setDisabled(True)
			self.albumInfoButton.connect(self.albumInfoButton, QtCore.SIGNAL("clicked()"), self.getFiles)
			albumInfoTextLayout.addWidget(self.albumInfoButton)
			albumInfoBox.resize(albumInfoBox.sizeHint())
			
			#
			#box na listę plików do wysłania
			#
			albumFilesBox=QtGui.QGroupBox(u"Pliki do wysłania.")
			albumFilesBoxLayout = QtGui.QVBoxLayout()
			albumFilesBox.setLayout(albumFilesBoxLayout)
			albumActionLayout.addWidget(albumFilesBox)
			albumFilesLabelsLayout = QtGui.QHBoxLayout()
			albumFilesLabelsLayout.setAlignment(QtCore.Qt.AlignLeft)
			albumFilesBoxLayout.addLayout(albumFilesLabelsLayout)
			albumFilesButtonsLayout = QtGui.QHBoxLayout()
			albumFilesButtonsLayout.setAlignment(QtCore.Qt.AlignLeft)
			albumFilesBoxLayout.addLayout(albumFilesButtonsLayout)
			
			albumFilesHostLabel = QtGui.QLabel(u"Społeczność: ")
			albumFilesLabelsLayout.addWidget(albumFilesHostLabel)
			self.albumFilesHost = QtGui.QLabel(u"Host")
			albumFilesLabelsLayout.addWidget(self.albumFilesHost)
			albumFilesAlbumLabel = QtGui.QLabel(u"| Album: ")
			albumFilesLabelsLayout.addWidget(albumFilesAlbumLabel)
			self.albumFilesAlbumName = QtGui.QLabel(u"| Album")
			albumFilesLabelsLayout.addWidget(self.albumFilesAlbumName)
			self.albumFilesAlbum = QtGui.QLabel(u"ID")
			albumFilesLabelsLayout.addWidget(self.albumFilesAlbum)
			#packSize
			packSizeLabel = QtGui.QLabel(u'Paczka: ')

			self.packSize = QtGui.QComboBox()
			self.packSize.setToolTip(u'Wybierz po ile zdjęć ma być wysyłanych.')
			self.packSize.addItems(('5','10','20','50'))
			self.packSize.setCurrentIndex(1)
			albumFilesButtonsLayout.addWidget(packSizeLabel)
			albumFilesButtonsLayout.addWidget(self.packSize)
			#
			#Upload files button
			#
			self.uploadButton= QtGui.QPushButton(QtGui.QIcon("icons/upload.png"), u'&Wyślij zdjęcia')
			self.uploadButton.connect(self.uploadButton, QtCore.SIGNAL("clicked()"), self.uploadFiles)	
			self.clearListButton = QtGui.QPushButton(u"Wyczyść listę")
			albumFilesButtonsLayout.addWidget(self.uploadButton)
			albumFilesButtonsLayout.addWidget(self.clearListButton)
			#
			#lista plików
			self.filesListBox = QtGui.QListWidget()
			self.filesListBox.setSelectionMode(2)
			albumFilesBoxLayout.addWidget(self.filesListBox)
			self.clearListButton.connect(self.clearListButton, QtCore.SIGNAL('clicked()'),self.filesListBox, QtCore.SLOT('clear()'))
			
			
			'''
			pasek postępu
			'''
			self.progressBox = self.myPB()
			self.progressBox.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding)
			albumBoxLayout.addWidget(self.progressBox)
##################################################################
#end albumu"
#######################################

			'''
			wstawianie głównych boxów
			'''
			mainLayout = QtGui.QVBoxLayout() 
			mainLayout.addWidget(self.loginBox)
			mainLayout.addWidget(self.logoutButton)
			mainLayout.addWidget(self.albumBox)
			mainLayout.addStretch()
			mainLayout.addWidget(self.statusBar)
			self.albumBox.hide()
			self.logoutButton.hide()
			self.setLayout(mainLayout)
			self.setWindowTitle(u"PySoQt v.0.2 Fotowysyłacz na socjum.pl")
			self.setMinimumSize(400, 100)
			

if __name__ == '__main__':
	socjum = Socjum()
	app =QtGui.QApplication(sys.argv)
	win = Win()
	win.show()#show function runs QWidget
	sys.exit(app.exec_())  
